package com.thorqq.translation.api;

import java.util.HashMap;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

public class TransGoogle extends TransApi
{
	private static final String	TRANS_API_HOST	= "http://translate.google.cn/translate_a/single";

	@Override
	protected String translate(String from, String to, String src)
	                throws Exception
	{
		Map<String, String> params = buildParams(src, from, to);

		Connection conn = Jsoup.connect(TRANS_API_HOST);
		conn.data(params);

    	conn.ignoreContentType(true);
    	Document doc = conn.post();

// en -> zh
//    	[
//    		[
//    			["认为你有网络安全照顾？", "Think You Have Cybersecurity Taken Care Of?", null, null, 3],
//    			["再想一想", "Think Again", null, null, 1]
//    		], null, "en"
//    	]    	

// zh -> en
//    	[
//    		[
//    			["A huge investment return was made by Jeff Dean's team-led translation project at Google Brain. ", "由Jeff Dean在Google Brain的团队领导的翻译项目获得巨大投资回报。", null, null, 3],
//    			["It is reported that Google Translate is now a paid API service, generating tangible income. ", "据悉，谷歌翻译现在是一个付费的API服务，产生了切实的收入。", null, null, 3],
//    			["More importantly, however, the Google Translate project helped Google speed up the creation of a common artificial intelligence platform that could be used to solve many other problems besides translation. ", "不过，更重要的是，谷歌翻译项目帮助谷歌加快了创建通用人工智能平台的速度，可以用于解决除翻译之外的许多其他问题。", null, null, 3],
//    			["Dean elaborates on Google's progress in this area and the services Google has built to help other companies with machine learning, even if they don't have enough resources to hire data scientists.", "Dean详细阐述了谷歌在这方面的进展，以及谷歌为帮助其他公司进行机器学习而建立的服务，即便他们没有足够的资源来雇佣数据科学家。", null, null, 3]
//    		], null, "zh-CN"
//    	]

    	StringBuffer buf = new StringBuffer();

    	String result = doc.body().text();
		JSONArray array1 = JSON.parseArray(result);
		JSONArray array2 = JSON.parseArray(array1.getString(0));
		for(Object obj : array2)
		{
			JSONArray array3 = (JSONArray)obj;
			buf.append(array3.getString(0));
		}

    	return buf.toString();	
    	
	}

	@Override
	public String enToZh(String src) throws Exception
	{
    	return translate("en", "zh-CN", src);
	}

	@Override
	public String zhToEn(String src) throws Exception
	{
    	return translate("zh-CN", "en", src);
	}

	
	private Map<String, String> buildParams(String query, String from, String to)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put("client", "gtx");
		params.put("q", query);
		params.put("sl", from);
		params.put("tl", to);
		params.put("dt", "t");

		return params;
	}

	@Override
    public String getVendor()
    {
	    return "Google";
    }
}
